//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "framework\fn_getMissionInstance.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;
private ["_InstanceList","_InstanceValues","_instance","_id","_index","_value"];
DEFAULT_PARAM(_id,0,TMF_SERVER_INSTANCE_ID);
_InstanceValues = [];
_instance = [];
if (typename _id == typename "") then {
	_InstanceList = JIPGETVAR(QGVAR(MISSION_INSTANCES),[]);
	_index = _InstanceList find _id;
	if (_index >= 0) then {
		_InstanceValues = JIPGETVAR(QGVAR(MISSION_INSTANCE_VALUES),[]);
		If (_index < count (_InstanceValues)) then {
			_InstanceValues = _InstanceValues select _index;
			// Now we check if we got the values back of the right instance
			_value = [_InstanceValues, TMF_HK_INSTANCE_ID,"",THIS_FILE] call FFUNC(hashGet);
			if (_value == _id) then {
				_instance = _InstanceValues;
			} else {
				ERROR_1("Found instance values do not match",ARR_3(_id,_index,_value));
			};
		} else {
			ERROR_1("Values index not found",ARR_3(_id,_index,""));
			_instance = (call FFUNC(hashEmpty));
			_instance = [_instance, TMF_HK_INSTANCE_ID,_id] call FFUNC(HashSet);
			_InstanceValues set [_index, _instance];
			JIPSETVAR(QGVAR(MISSION_INSTANCE_VALUES),_InstanceValues);
			TRACE_1("Created new Instance Values",ARR_2(_index, _id));
		};
	} else {
		ERROR_1("Instance not found",ARR_3(_id,_index,""));
		_index = count _InstanceList;
		_InstanceList set [_index, _id];
		_instance = (call FFUNC(hashEmpty));
		_instance = [_instance, TMF_HK_INSTANCE_ID,_id] call FFUNC(HashSet);
		_InstanceValues set [_index, _instance];
		JIPSETVAR(QGVAR(MISSION_INSTANCES),_InstanceList);
		JIPSETVAR(QGVAR(MISSION_INSTANCE_VALUES),_InstanceValues);
		TRACE_1("Created new Instance",ARR_2(_index, _id));
	};
};
TRACE_1("End",ARR_2(count _instance,_instance));
TMFPROFILERSTOP;
_instance;
